package library

import (
	"github.com/astaxie/beego"
	"github.com/garyburd/redigo/redis"
)

type Redis struct {
	instance redis.Conn
	rBuild   RedisBuild
}

type RedisBuild struct {
	db     int
	expire int
}

var err error

func (self *Redis) GetInstance() *Redis {
	if self.instance == nil {
		host := beego.AppConfig.String("host")
		port := beego.AppConfig.String("port")
		self.instance, err = redis.Dial("tcp", host+":"+port)
		if err != nil {
			beego.Error(err.Error())
		}
	}
	return self
}

func (self *Redis) Set(key string, value interface{}) interface{} {
	self.getSelect()
	reply, _ := self.instance.Do("set", key, value)
	if self.rBuild.expire > 0 {
		self.instance.Do("expire", key, self.rBuild.expire)
	}
	return reply
}

func (self *Redis) Get(key string) interface{} {
	self.getSelect()
	reply, err := self.instance.Do("get", key)
	if err != nil {
		return ""
	}
	return reply
}

func (self *Redis) Select(db int) *Redis {
	self.rBuild.db = db
	return self
}

func (self *Redis) Expire(time int) *Redis {
	self.rBuild.expire = time
	return self
}

func (self *Redis) getSelect() {
	self.instance.Do("select", self.rBuild.db)
}
